package com.fzfnn.scrapbook.service.impl;

import com.fzfnn.scrapbook.dto.JournalDto.JournalDto;
import com.fzfnn.scrapbook.entity.CollectionFolder;
import com.fzfnn.scrapbook.entity.User;
import com.fzfnn.scrapbook.mapper.CollectionMapper;
import com.fzfnn.scrapbook.mapper.UserMapper;
import com.fzfnn.scrapbook.service.CollectionService;
import com.fzfnn.scrapbook.util.R;
import com.fzfnn.scrapbook.vo.CollectionCountVO;
import com.fzfnn.scrapbook.vo.JournalVo;
import com.fzfnn.scrapbook.vo.PersonalhomepageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CollectionServiceImpl implements CollectionService {

    @Autowired
    private CollectionMapper collectionMapper;
    @Autowired
    private RedisTemplate<String, String> redisMail;
    @Autowired
    private UserMapper userMapper;

    @Override
    public R createFolder(String token, String name) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        long userIds = Long.parseLong(userId);
        collectionMapper.createFolder(userIds, name);
        Long folderId = collectionMapper.getFolderIdByName(userIds, name);
        if (folderId == null) {
            return R.errorMsg("收藏夹创建失败");
        }
        return R.success("收藏夹创建成功", folderId);
    }

    @Override
    public R getUserFolders(String token, Integer userIds) {
        // 从 Redis 获取当前登录用户 ID
        String userIdStr = redisMail.opsForValue().get("token:" + token);
        if (userIdStr == null) {
            return R.errorMsg("登录信息无效");
        }

        Long currentUserId;
        try {
            currentUserId = Long.parseLong(userIdStr);
        } catch (NumberFormatException e) {
            return R.errorMsg("用户ID格式错误");
        }

        // 如果 userIds 为 null，使用当前登录用户 ID，否则使用传入的 userIds
        Long targetUserIdLong = (userIds == null) ? currentUserId : Long.valueOf(userIds);

        // 校验目标用户是否存在
        User targetUser = userMapper.selectUserById(targetUserIdLong);
        if (targetUser == null) {
            return R.errorMsg("目标用户不存在");
        }
        // 获取用户所有收藏夹
        List<CollectionFolder> folders = collectionMapper.getFoldersByUserId(targetUserIdLong);
        // 提取收藏夹ID列表
        List<Long> folderIds = folders.stream()
                .map(CollectionFolder::getId)
                .collect(Collectors.toList());
        if (folderIds.isEmpty()) {
            return R.success("data", Collections.emptyList()); // 没有收藏夹，直接返回空
        }
        // 批量获取每个收藏夹的收藏数量
        List<CollectionCountVO> counts = collectionMapper.getCollectionCountsByFolderIds(folderIds);
        // 构建 Map 用于快速查找
        Map<Long, Integer> countMap = counts.stream()
                .collect(Collectors.toMap(
                        CollectionCountVO::getFolderId,
                        CollectionCountVO::getCount
                ));
        // 将数量赋值给每个收藏夹对象
        for (CollectionFolder folder : folders) {
            folder.setCollectionCount(countMap.getOrDefault(folder.getId(), 0));
        }
        return R.success("data", folders);
    }



    @Override
    public R addToCollection(String token, Long journalId, Long folderId) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        long userIds = Long.parseLong(userId);
        // 可选：先判断是否已经收藏
        if (collectionMapper.isCollected(userIds, journalId)) {
            return R.errorMsg("手账已收藏");
        }
        collectionMapper.addCollection(userIds, journalId, folderId);
        return R.successMsg("收藏成功");
    }

    @Override
    public R isCollected(String token, Long journalId) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        long userIds = Long.parseLong(userId);
        return R.success("data", collectionMapper.isCollected(userIds, journalId));
    }

    @Override
    public R removeFromCollection(String token, Long journalId) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        long userIds = Long.parseLong(userId);
        collectionMapper.removeCollection(userIds, journalId);
        return R.successMsg("取消收藏成功");
    }
    @Override
    public R deleteFolder(Long folderId, String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        long userIds = Long.parseLong(userId);
        // 先删除该收藏夹下的所有收藏记录
        collectionMapper.deleteCollectionsByFolderId(folderId, userIds);
        // 再删除收藏夹本身
        collectionMapper.deleteFolderById(folderId, userIds);
        return R.successMsg("删除收藏夹成功");
    }

    @Override
    public R getCollectionsByFolder(String token, Long folderId) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        long userIds = Long.parseLong(userId);
        List<JournalVo> collections = collectionMapper.getCollectionsByFolderId(userIds, folderId);
        return R.success("data", collections);
    }

    @Override
    public R updateFolderName(String token, Long folderId, String name) {
        if (folderId == null || name == null || name.trim().isEmpty()) {
            return R.errorMsg("参数不能为空");
        }

        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }

        String trimmedName = name.trim();

        // 查询当前收藏夹名称
        String currentName = collectionMapper.getFolderNameById(Long.valueOf(userId), folderId);
        if (currentName == null) {
            return R.errorMsg("收藏夹不存在或无权限访问");
        }

        if (trimmedName.equals(currentName)) {
            return R.errorMsg("新名称与原名称相同，无需修改");
        }

        int updatedRows = collectionMapper.updateFolderName(Long.valueOf(userId), folderId, trimmedName);
        if (updatedRows == 0) {
            return R.errorMsg("更新失败，请稍后再试");
        }

        return R.successMsg("修改收藏夹名称成功");
    }



}
